#!coding:utf-8
'''
Created on Oct 17, 2012

@author: join
'''

import logging
from lottery_terminal.models import Account,Trade,TicketConstant,TicketLoan,SevenColor,ThreeD,FiveBall,SixPlusOne,\
    SerialTerminalNumber, SystemSettings
from lottery_terminal.common import utils,Constant
from lottery_terminal.views import  type_dict1,type_dict3, trademethod_dict
from django.http import HttpResponse
import datetime
from multiprocessing.synchronize import Lock
import json

type_dict4 = {Constant.DANSHI:u'单式', Constant.FUSHI:u'复式', Constant.BAOHAO:u'包号',Constant.HEZHI:u'和值',Constant.DANTUO:u'胆托' }

type_dict5 = {Constant.OneStart:u'一星', Constant.TwoStart:u'二星', Constant.ThreeStart:u'三星',Constant.FourStart:u'四星',Constant.FiveStart:u'五星' ,\
              Constant.TwoStart_Check:u'二星复选', Constant.ThreeStart_Check:u'三星复选', Constant.FourStart_Check:u'四星复选',\
              Constant.FiveStart_Check :u'五星复选',Constant.TwoStart_GroupSelect:u'二星组选',Constant.BigSmall_SingleDouble :u'大小单双',\
              Constant.FiveStart_AllCheck:u'五星通选',Constant.CheckOne:u'任选一',Constant.CheckTwo:u'任选二',\
              Constant.ThreeStart_ForThree:u'三星组三',Constant.ThreeStart_ForSix :u'三星组六',}
type_dict6 = {Constant.PuTong:u'单选'}
type_dict7 = {Constant.DanXuan3:u'单选3',Constant.ZuXuan3:u'组选3',Constant.ZuXuan6:u'组选6'}

LOG = logging.getLogger('terminal')

@utils.ajaxrender
def submit_recharge(req):
    '''提交充值，调用银联接口'''
    mac = req.POST.get('mac')
    money = req.POST.get('money')
    if not mac or not money:
        return u'非法操作',400
    accounts=Account.objects.filter(mac=mac,deleted=False)
    account = None
    if accounts:
        account = accounts[0]
    money = float(money)
    bankratios = SystemSettings.objects.filter(itemname="bank_ratio")
    if bankratios:
        bankratio = bankratios[0].itemvalue
        bankratio = float(bankratio)
    else:
        bankratio = 0.01
    if not account:
        return u'账户错误，充值失败',500
    balance = account.balance+money-money*bankratio
    account.balance = balance
    account.save()
    Trade.objects.create(tradeType=0,tradeMethod=0,tradeAmount=(money-money*bankratio),accountid=account,tradeTime=datetime.datetime.now(),status=2)
    
    now = utils.convert_datetime_to_str(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
    LOG.exception("submit_recharge:add balance to account:%s,money:%s,new balance:%s,time:%s"%(account.account,money,balance,now))
    
    result = {'balance':balance}
    return json.dumps(result),200

def get_sn(req):
    '''获取易宝终端号，终端序列号'''
    result = ''
    lock = Lock()
    lock.acquire()
    try:
        stns = SerialTerminalNumber.objects.filter(is_used=False,delete=False) #未使用的终端号序列号
        if stns:
            stn = stns[0]
            tn = stn.terminal_number #终端号
            sn = stn.serial_number #序列号
            result = '%s#%s'%(tn,sn)
            stn.is_used=True
            stn.save()
    except Exception as e:
        LOG.exception('to retrive terminal number and serial number failed:%s'%e)
    finally:
        lock.release()
        
    return HttpResponse(result)

def get_sn2(req,licensecode):
    '''为解决密钥问题，通过验证licensecode重新获取易宝终端号，序列号'''
    result = ''
    lock = Lock()
    lock.acquire()
    try:
        stns = SerialTerminalNumber.objects.filter(is_used=True,licensecode=licensecode,deleted=False)
        if not stns:
            stns = SerialTerminalNumber.objects.filter(is_used=False,deleted=False) #未使用的终端号序列号
            stn = stns[0]
            stn.is_used = True
            stn.licensecode = licensecode
            stn.save()
            result = '%s#%s'%(stn.terminal_number, stn.serial_number)
    except Exception as e:
        LOG.exception('get_sn2 to retrive terminal number and serial number failed:%s'%e)
    finally:
        lock.release()
    return HttpResponse(result)

@utils.render
def sale_info(request,currentpage,mac):
    '''该机器上的历史的销售记录'''
    currentpage=int(currentpage)
    try:
        year=cur_year = int(str(datetime.date.today())[0:4])
        month=cur_month = int(str(datetime.date.today())[5:7])
        day = int(str(datetime.date.today())[8:10])
#        
        if cur_month==1:
            start_time1 = datetime.datetime(cur_year-1,12,1) #上月
        else:
            start_time1 = datetime.datetime(cur_year,cur_month-1,1) #上月
        end_time1 = datetime.datetime(cur_year,cur_month,1)
        
        start_time2 = datetime.datetime(cur_year,cur_month,1) #当月
        if cur_month+1>12:
            month = 0
            year = cur_year+1
        end_time2 = datetime.datetime(year,month+1,1) #当月
        
        start_time3 = datetime.datetime(cur_year,cur_month,day,0,0,0) #当日
        end_time3 = datetime.datetime(cur_year,cur_month,day,23,59,59)
        
        accountid=Account.objects.filter(mac=mac,deleted=False).all()[0]
        sale_last_month = Trade.objects.filter(deleted=False,tradeType=Constant.TRADE_BUY_LOTTERY,status=Constant.TRADE_SUCCESSED,
                                          updated_at__gte=start_time1,updated_at__lte=end_time1,accountid=accountid).extra(select={'amount':'sum(tradeAmount)'}).values('amount')
#        sale_last_month = sum([trade.tradeAmount for trade in trades_last_month])
        sale_cur_month = Trade.objects.filter(deleted=False,tradeType=Constant.TRADE_BUY_LOTTERY,status=Constant.TRADE_SUCCESSED,
                                          updated_at__gte=start_time2,updated_at__lte=end_time2,accountid=accountid).extra(select={'amount':'sum(tradeAmount)'}).values('amount')
#        sale_cur_month = sum([trade.tradeAmount for trade in trades_cur_month])
        sale_total = Trade.objects.filter(deleted=False,tradeType=Constant.TRADE_BUY_LOTTERY,status=Constant.TRADE_SUCCESSED,
                                          accountid=accountid).extra(select={'amount':'sum(tradeAmount)'}).values('amount')

        sale_cur_day = Trade.objects.filter(deleted=False,tradeType=Constant.TRADE_BUY_LOTTERY,status=Constant.TRADE_SUCCESSED,
                                          updated_at__gte=start_time3,updated_at__lte=end_time3,accountid=accountid).extra(select={'amount':'sum(tradeAmount)'}).values('amount')
#        sale_cur_day = sum([trade.tradeAmount for trade in trades_cur_day])
        
        params = {'accountid':accountid,'deleted': False,'tradeType':Constant.TRADE_BUY_LOTTERY}
        datalist=[]
        result={}
        tradesall = Trade.objects.filter(**params).count()
        if tradesall%10 == 0:
            allpage=tradesall/10
        else:
            allpage=tradesall/10+1
        pagesize=10
        if currentpage==0:
            currentpage=1
        if currentpage>allpage:
            currentpage=allpage
        startnum=(currentpage-1)*pagesize
        endnum=currentpage*pagesize
        if endnum>tradesall:
            trades = Trade.objects.filter(**params).order_by('-tradeTime')[startnum:tradesall]
        trades = Trade.objects.filter(**params).order_by('-tradeTime')[startnum:endnum]
        for trade in trades:
            if trade.tradeTicketType is None:
                trade.tradeTicketType="暂没种类"
            try:
                periodid = trade.period.periodid
            except:
                periodid = ''
            datalist.append({
                            'tradeid': trade.id,
                            'ticktype':type_dict3.get(trade.tradeTicketType),
                            'period':periodid,                                 
                            'tradamount':trade.tradeAmount,
                            'tradeMethod':trademethod_dict.get(trade.tradeMethod),
                            'tradtime':utils.convert_datetime_to_str(trade.tradeTime, "%Y-%m-%d %H:%M:%S"),
                            'status':type_dict1.get(trade.status),
                            })
          
        result['trades']=datalist
        result['allpage']=allpage
        result['allcount']=tradesall
        result['currentpage']=currentpage
        result['saletotal'] = 0.0 if not sale_total[0].get('amount') else sale_total[0].get('amount')
        result['saleawards'] = result['saletotal']*accountid.commissionRatio
        result['balance'] = accountid.balance
        result['sale_last_month'] = 0.0 if not sale_last_month[0].get('amount') else sale_last_month[0].get('amount')
        result['sale_cur_month'] = 0.0 if not sale_cur_month[0].get('amount') else sale_cur_month[0].get('amount')
        result['sale_cur_day'] = 0.0 if not sale_cur_day[0].get('amount') else sale_cur_day[0].get('amount')
        return 'sale_info.html', result
    except Exception as e:
        LOG.exception("an exception occured in sale_info:%s"%e)

     
def register_card(request,cardNo,mac):
    try:
        if Account.objects.filter(mac=mac):
            return HttpResponse("already exist this mac address!")
        if  Account.objects.filter(account=cardNo):
            return HttpResponse("already exist this card number!")
            
        Account.objects.create(account=cardNo,loginname=cardNo, password=utils.getMD5Str(cardNo), balance=0.0, accountType=0,mac=mac)
        return HttpResponse("ok")
    except:
        return HttpResponse("error")
    